use std::{rc::Rc, cell::RefCell, path::Path, fs::metadata};

use crate::{native, rtda::{Frame, Object, heap::string_pool}};

pub fn init() {
    native::register("java/io/UnixFileSystem", "canonicalize0", "(Ljava/lang/String;)Ljava/lang/String;", canonicalize0);
	native::register("java/io/UnixFileSystem", "getBooleanAttributes0", "(Ljava/io/File;)I", get_boolean_attributes0);
}

// private native String canonicalize0(String path) throws IOException;
// (Ljava/lang/String;)Ljava/lang/String;
fn canonicalize0(frame: Rc<RefCell<Frame>>) {
    let vars = frame.borrow().get_local_vars();
    let mut path = vars.borrow().get_ref(1);

    // TODO 231010 暂未实现filepath.Clean(goPath),直接添加path
	// goPath := heap.GoString(path)
	// goPath2 := filepath.Clean(goPath)
	// if goPath2 != goPath {
	// 	path = heap.JString(frame.Method().Class().Loader(), goPath2)
	// }

	// stack := frame.OperandStack()
	// stack.PushRef(path)
    // let rs_path = StringPool::rs_string(path);

    let stack = frame.borrow().get_operand_stack();
    stack.borrow_mut().push_ref(path);
    
}

// public native int getBooleanAttributes0(File f);
// (Ljava/io/File;)I
fn get_boolean_attributes0(frame: Rc<RefCell<Frame>>) {
    let vars = frame.borrow().get_local_vars();
	let f = vars.borrow().get_ref(1).unwrap();
	let path = _get_path(f);

	// todo
	let mut attributes0 = 0;
	let path = Path::new(&path);
	let metadata = metadata(path);
	// 判断文件是否存在，暂不判断是否有权限访问，无权访问当作不存在。
	if let Ok(metadata) = metadata {
		attributes0 |= 0x01;
		// 是否是文件夹
		if metadata.is_dir() {
			attributes0 |= 0x04;
		}
	}

	let stack = frame.borrow().get_operand_stack();
	stack.borrow_mut().push_int(attributes0);
}

fn _get_path(file_obj: *mut Object) -> String {
	let ptah_str = unsafe { &*file_obj }.get_ref_var("path", "Ljava/lang/String;");
	string_pool::rs_string(ptah_str.unwrap())
}

// fn _exists(path: &Path) -> bool {
// 	// let metadata = Metadata::;
// 	// if metadata.is_err() {
// 	// 	return true;
// 	// }
// 	// if metadata.unwrap() {
		
// 	// }

// 	false

// }